package com.hmdp.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * @author zcf
 */
@Component
@Slf4j
public class CacheClient {
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
    private final StringRedisTemplate stringRedisTemplate;

    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    //一.普通的设置缓存
    public void setCache(String key, Object value, Long time, TimeUnit timeUnit) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, timeUnit);
    }

    //二.逻辑过期处理，缓存重建写数据的方法
    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit timeUnit) {
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(timeUnit.toSeconds(time)));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }


    public <R, N> R queryWithLogicalExpire(Class<R> rClass, String keyPrefix, Function<N, R> dbFallback, Long time, N id, TimeUnit timeUnit) {
        String key = keyPrefix + id;
        //1.先去redis查缓存
        String json = stringRedisTemplate.opsForValue().get(key);
        //2,判断是否命中
        if (StrUtil.isBlank(json)) {
            return null;
        }
        //3.命中
        //3.判断是否过期
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        R r = JSONUtil.toBean((JSONObject) redisData.getData(), rClass);
        LocalDateTime expireTime = redisData.getExpireTime();
        if (expireTime.isAfter(LocalDateTime.now())) {
            //表示未过期，直接返回数据
            return r;
        }
        //4.过期，进行缓存重建
        //4.获取互斥锁
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        Boolean aBoolean = tryLock(lockKey);
        if (aBoolean) {
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    //查询数据库，进行重建
                    R r1 = dbFallback.apply(id);
                    this.setWithLogicalExpire(key, r1, time, timeUnit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    unlock(lockKey);
                }
            });
        }

        //重建的时候先返回旧数据、
        return r;
    }


    //三------解决缓存穿透

    public <R, N> R queryWithPassThrough(N id, Class<R> rClass, String keyPrefix, Long time, TimeUnit timeUnit, Function<N, R> dbFallback) {
        String key = keyPrefix + id;
        //1.先去查redis
        String json = stringRedisTemplate.opsForValue().get(key);
        //2.判断是否存在

        //2.1
        if (StrUtil.isNotBlank(json)) {
            //存在，就返回
            return JSONUtil.toBean(json, rClass);
        }
        //判断是否为空值
        if (json != null) {
            //是空值，返回一个null
            return null;
        }

        //2.2-不存在
        //2.3查询数据库
        R r = dbFallback.apply(id);
        if (r == null) {
            //将空值写入redis
            stringRedisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        //2.4数据库查得到，写入redis
        this.setCache(key, r, time, timeUnit);
        return r;
    }

    //四 利用互斥锁解决缓存击穿
    public <R, N> R queryWithMutex(String keyPrefix, N id, Long time, Class<R> rClass, Function<N, R> dbFallback, TimeUnit timeUnit) {
        String key = keyPrefix + id;
        //1.查询redis
        String json = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(json)) {
            //存在，直接返回
            return JSONUtil.toBean(json, rClass);
        }
        if (json != null) {
            //是空值
            return null;
        }
        //不存在，实现重建
        //1.1获取互斥锁
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        R r = null;
        try {
            Boolean aBoolean = tryLock(lockKey);
            //1.2获取锁失败，休眠一会，再获取
            if (!aBoolean) {
                Thread.sleep(50);
                return queryWithMutex(keyPrefix, id, time, rClass, dbFallback, timeUnit);
            }
            //1.3获取锁成功，进行重建
            r = dbFallback.apply(id);
            if (r == null) {
                //空值
                stringRedisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            //不是空值，就直接写入redis
            this.setCache(key, r, time, timeUnit);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            unlock(lockKey);
        }

        return r;
    }

    //获取锁
    private Boolean tryLock(String key) {
        return stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
    }

    //释放锁
    private void unlock(String key) {
        stringRedisTemplate.delete(key);
    }
}
